var supplierObj = [];
var limit = 15;
var tid;
var orgObj = convertOrgToObj(orgList);
layui.use(['laypage', 'table', 'form'], function(){
    var table = layui.table;
    var form = layui.form;

    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'orgId', title: '公司名称', width:280, fixed: 'left', align: 'center',templet:function (val) {
                return orgObj[val.orgId];
            }}
            ,{field: 'materialName', title: '材料名称', width: 420, fixed: 'left',align: 'center',templet: function (val) {
                if (isNull(val.materialName)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.materialName + '</div>';
            }}
            ,{field: 'materialName', title: '供应商名称', width: 420, fixed: 'left',align: 'center',templet: function (val) {
                if (isNull(val.supplierName)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.supplierName + '</div>';
            }}
            ,{field: 'weight', title: '固定重量', width: 240, align: 'center'}
            ,{field: 'status', title: '状态', width:200, align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'startDate', title: '生效时间', width: 240, align: 'center'}
            ,{field: 'endDate', title: '失效时间', width: 240, align: 'center'}
            ,{field: 'remark', title: '备注', width: 580, align: 'center',templet: function (val) {
                if (isNull(val.remark)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.remark + '</div>';
            }}
            ,{field: 'creator', title: '创建人', width: 240, align: 'center'}
            ,{field: 'createTime', title: '创建时间', width: 240, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 260, align:'center', templet:function (val) {
                var str = '';
                if (val.status == 0){
                    str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">作废</a>';
                }else{
                    str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs">启用</a>';
                }
                return str;
            }}
        ]
    ];

    table.render({
        elem: '#body-list'
        ,url: '/mainmateriallimit/page'
        ,method: 'post'
        ,page: true
        ,contentType: 'application/json'
        ,cols: todoCols
        ,limit: limit
        ,limits: [15,30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit,
            orgId:$('.search-origin').val(),
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res);
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"

        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){
            var id = data.id;
            var status = data.status;
            var tip = '是否要启用？';
            if (status == 0)
                tip = '是否要作废？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option =  '{"id": '+id+', "status":'+updateStatus+'}';
                save(option, "/mainmateriallimit/updatestatus");
            }, function(index){
            });
        }
    });

    form.on('select(search-status)', function(data) {
        $(".btn-query").trigger("click");
    });

    form.on('select(search-supplier)', function(data) {
        $(".btn-query").trigger("click");
    });

    form.on('select(search-material)', function(data) {
        $(".btn-query").trigger("click");
    });

    form.on('select(search-origin)', function(data) {
        getSupplierByOrgId();
        getMaterialByOrgId();
        $(".btn-query").trigger("click");
    });

    $('.btn-query').on('click', function () {//搜索按钮
        var searchVal = $('.search-text').val();
        var status = $('.search-status').val();
        var orgId = $('.search-origin').val();
        var supplierId = $('.search-supplier').val();
        var materialId = $('.search-material').val();

        var option = {page:1,limit:limit};
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(orgId))
            option['orgId'] = orgId;
        if (!isNull(status))
            option['status'] = status;
        if (!isNull(supplierId))
            option['supplierId'] = supplierId;
        if (!isNull(materialId))
            option['materialId'] = materialId;
        table.reload('body-list', {
            where: option
        });
    });


    function save(option, url) {//新增或修改
        var loading = layer.load(1);
        console.log(option);
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            data: option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    layer.msg("保存成功!");
                    table.reload('body-list', { where: {offset:0,curr:1,
                            limit: limit,
                            orgId:$('.search-origin').val() }});
                    form.render();
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }


    //初始化执行一次
    getSupplierByOrgId();
    getMaterialByOrgId();

    //加载供应商信息
    function getSupplierByOrgId() {
        var obj = '{"orgId": '+$(".search-origin").val()+'}';
        var loading = layer.load(1);
        $.ajax({
            url: '/mainmateriallimit/getSupplierList',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            success: function (res) {
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择供应商</option>';
                    $.each(data, function (i, v) {
                        html += '<option value="' + v.id + '">' + v.name + '</option>';
                    });
                    $('.search-supplier').html(html);
                } else {
                    $('.search-supplier').html('<option value="">暂无数据</option>');
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }


    //加载材料下拉框
    function getMaterialByOrgId() {
        var obj = '{"orgId": '+$(".search-origin").val()+'}';
        var loading = layer.load(1);
        $.ajax({
            url: '/mainmateriallimit/getMaterialByOrgId',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            success: function (res) {
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择材料</option>';
                    $.each(data, function (i, v) {
                        html += '<option value="' + v.materialId + '">' + v.nameNorms + '</option>';
                    });
                    $('.search-material').html(html);
                } else {
                    $('.search-material').html('<option value="">暂无数据</option>');
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }

    $(document).keyup(function (event) {
        if (event.keyCode == 13) {
            $(".btn-query").trigger("click");
        }
    });
});